<script setup lang="ts">
import Motion from './motion'
import { useRenderIcon } from '@/components/ReIcon/src/hooks'
import { ref, reactive } from 'vue'

import { bindRules } from './rule'
import type { FormInstance } from 'element-plus'
import { captchaApi, smsApi, bindApi } from '@/api/auth'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

import captchaError from '@/assets/captcha_error.png'
import Phone from '@iconify-icons/ri/smartphone-line'
import Message from '@iconify-icons/ep/message'
import Picture from '@iconify-icons/ep/picture-rounded'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
const ruleForm = reactive({
  phone: '',
  code: '',
  password: '',
  captcha: ''
})

const captchaGetting = ref(false)
const captchaImg = ref()
function getCaptcha() {
  captchaGetting.value = true
  captchaApi()
    .then((res) => {
      captchaImg.value = res.data
      captchaGetting.value = false
    })
    .catch((error) => {
      ElMessage.error(error.message)
      captchaGetting.value = false
    })
}
const svgReg = /^<svg/

const codeGetting = ref(false)
const codeGeted = ref(false)
const codeTimed = ref(60)
const getCode = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validateField(['phone', 'captcha'], (valid, fields) => {
    if (valid) {
      codeGetting.value = true
      smsApi({
        phone: ruleForm.phone,
        captcha: ruleForm.captcha,
        id: route.query.id
      })
        .then((res) => {
          codeGetting.value = false
          if (res.status != 200) {
            ElMessage.error(res.message ?? '图形验证码有误，请重试')
            captchaImg.value = res.data
            return
          }
          ElMessage({ message: '验证码已发送，请注意查收', type: 'success' })
          codeGeted.value = true
          codeTimed.value = 60
          var codeTimer = setInterval(() => {
            if (codeTimed.value > 0) {
              codeTimed.value = codeTimed.value - 1
            } else {
              clearInterval(codeTimer)
            }
          }, 1000)
        })
        .catch((error) => {
          codeGetting.value = false
          ElMessage.error(error.message)
        })
    }
  })
}

const ruleFormRef = ref<FormInstance>()
const loading = ref(false)
const onLogin = async (formEl: FormInstance | undefined) => {
  loading.value = true
  if (!formEl) return
  await formEl.validate((valid: boolean, fields: any) => {
    if (valid) {
      bindApi({
        phone: ruleForm.phone,
        id: route.query.id,
        code: ruleForm.code
      })
        .then((res) => {
          loading.value = false
          if (res.status != 200) {
            ElMessage.error(res.message ?? '验证码有误，请重试')
            return
          }
          var user = useUserStore()
          user.setToken(res.data.token)
          user.setUserInfo(res.data)
          router.push({ name: 'home' })
          ElMessage({ message: '绑定成功', type: 'success' })
        })
        .catch((error) => {
          loading.value = false
          ElMessage.error(error.message)
        })
    } else {
      loading.value = false
      return fields
    }
  })
}
if (!route.query.id) {
  router.replace('/error/403')
} else {
  getCaptcha()
}
</script>

<template>
  <div style="padding: 2em">
    <div class="line_center">
      <img alt="Vue logo" class="logo" src="@/assets/logo.svg" width="48" height="48" />
    </div>
    <div class="line_center">
      <Motion>
        <h2 class="title">绑定手机号</h2>
      </Motion>
    </div>

    <el-form ref="ruleFormRef" :model="ruleForm" :rules="bindRules" size="large">
      <Motion :delay="100">
        <el-form-item prop="phone">
          <el-input
            clearable
            v-model="ruleForm.phone"
            placeholder="手机号码"
            :prefix-icon="useRenderIcon(Phone)"
          />
        </el-form-item>
      </Motion>

      <Motion :delay="150">
        <el-form-item prop="captcha">
          <el-input
            clearable
            v-model="ruleForm.captcha"
            placeholder="图形验证码"
            :prefix-icon="useRenderIcon(Picture)"
          >
            <template #append>
              <div class="captcha">
                <el-button v-if="captchaGetting" loading circle></el-button>
                <div
                  id="captcha"
                  v-html="captchaImg"
                  @click="getCaptcha"
                  v-else-if="captchaImg != null"
                ></div>
                <img class="captcha" v-else @click="getCaptcha" :src="captchaError" />
              </div>
            </template>
          </el-input>
        </el-form-item>
      </Motion>

      <Motion :delay="200">
        <el-form-item prop="code">
          <el-input
            clearable
            v-model="ruleForm.code"
            placeholder="短信验证码"
            :prefix-icon="useRenderIcon(Message)"
          >
            <template #append>
              <div class="btn_code">
                <el-button class="btn_code" v-if="codeGetting" type="primary" loading
                  >发送中</el-button
                >
                <el-button class="btn_code" v-else-if="!codeGeted" @click="getCode(ruleFormRef)"
                  >获取验证码</el-button
                >
                <div class="btn_code" v-else-if="codeTimed > 0">{{ codeTimed }}s</div>
                <el-button class="btn_code" v-else @click="getCode(ruleFormRef)"
                  >重发验证码</el-button
                >
              </div>
            </template>
          </el-input>
        </el-form-item>
      </Motion>

      <Motion :delay="250">
        <div class="btn_container">
          <el-button
            class="btn"
            size="default"
            type="primary"
            :loading="loading"
            @click="onLogin(ruleFormRef)"
          >
            确定
          </el-button>
        </div>
      </Motion>
    </el-form>
  </div>
</template>
<!-- <style scoped>
@import url('@/style/login.css');
</style> -->
<style scoped>
.line_center {
  display: flex;
  justify-content: center;
  align-items: center;
}
.logo {
  margin-top: 40px;
  margin-bottom: 20px;
}
.height_full {
  height: 100vh;
}
.btn {
  width: 100%;
  margin-top: 14px;
}
.captcha {
  width: 120px;
  height: 40px;
}
.btn_code {
  padding-left: 20px;
  padding-right: 20px;
}
.title {
  font-size: 22px;
  margin-bottom: 40px;
}
</style>

<style>
.captcha svg {
  width: 120px;
  height: 40px;
}
</style>
